package chainOfResponsibility;

import gameBasics.GameObject;
import gameLevel.GameLevelControl;
import object.CommandPost;
import tank.bullet.Bullet;
import tank.bullet.BulletGroup;
import tank.explosion.Explosion;

public class BulletCommandPostCollider implements Collider{

    /**
     * 炮弹与指挥所碰撞
     * @param o1 炮弹对象
     * @param o2 指挥所对象
     */
    @Override
    public boolean collide(GameObject o1, GameObject o2) {
        if(o1 instanceof Bullet bullet && o2 instanceof CommandPost commandPost){
            return !collideWith(bullet, commandPost);
        } else if (o1 instanceof CommandPost && o2 instanceof Bullet) {
            return !collide(o2, o1);
        }

        return true;
    }

    /**
     * 炮弹与指挥所的碰撞检测
     * @param bullet 炮弹对象
     * @param commandPost 指挥所对象
     */
    private boolean collideWith(Bullet bullet, CommandPost commandPost) {
        if(bullet.getBulletGroup() == BulletGroup.GOOD) return false;

        if(bullet.getRectangle().intersects(commandPost.getRectangle())){
            commandPost.die();  //指挥所消亡
            bullet.die();       //炮弹消亡
            new Explosion(commandPost.x + commandPost.WIDTH / 2 - Explosion.WIDTH / 2, commandPost.y + commandPost.HEIGHT / 2 - Explosion.HEIGHT / 2);
            //处理碰撞结果
            collideResult();

            return true;        //相撞
        }

        return false;
    }

    /**
     * 炮弹与指挥所的碰撞结果
     * 游戏失败的第二个判断条件
     */
    private void collideResult(){
        GameLevelControl.gameOverState = true;
    }

}
